#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/19 9:27
# @Author  : Tom_zc

import os
import re
import sys
import click
import logging

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, "utils"))
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")

from utils.obs_helper import ObsHelper
from utils.common import func_retry

class PipeLineLogHelper:

    def __init__(self, ak, sk, obs_endpoint, obs_bucket_name):
        self.obs_helper = ObsHelper(ak, sk, obs_endpoint)
        self.obs_bucket_name = obs_bucket_name

    def _get_bucket_key(self, filename):
        match = re.search(r'^.*_([^_]*)\.deb$', filename)
        tag = match.group(1) if match else None
        return "{}/{}".format(tag, filename)

    @func_retry()
    def upload_obs(self, process, filename):
        bucket_key = self._get_bucket_key(filename)
        logging.info("upload to obs: {}".format(bucket_key))
        logging.info("path: {}".format(process))
        self.obs_helper.upload_file(self.obs_bucket_name, bucket_key, process)


@click.command()
@click.option("--process", help='The progress of step')
@click.option("--filename")
def main(process, filename):
    ak = os.getenv("ak")
    sk = os.getenv("sk")
    obs_endpoint = os.getenv("obs_endpoint")
    obs_bucket_name = os.getenv("obs_bucket_name")

    obsHelper = PipeLineLogHelper(ak, sk, obs_endpoint, obs_bucket_name)
    obsHelper.upload_obs(process, filename)

    sys.exit(0)


if __name__ == '__main__':
    main()
